package org.example;

import java.io.*;

public class SerializeTest {
    private static final String PATH = "student.txt";
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        File file = new File(PATH);
        if(!file.exists()){
            file.createNewFile();
        }
        serializeStudent();
        readStudent();
    }

    private static void readStudent() throws IOException, ClassNotFoundException {
        DataInputStream dataInputStream = new DataInputStream(new FileInputStream(PATH));
        int len = dataInputStream.readInt();
        byte[] buff = new byte[len];
        dataInputStream.read(buff);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buff);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Student student = (Student) objectInputStream.readObject();
        System.out.println(student);

    }

    private static void serializeStudent() throws IOException {
        Student student = new Student(1, "zhangsan");
        byte[] arr = null;
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){
            objectOutputStream.writeObject(student);
            arr = byteArrayOutputStream.toByteArray();
        }
        try(OutputStream outputStream = new FileOutputStream(PATH);
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream)){
            dataOutputStream.writeInt(arr.length);
            System.out.println(arr.length);
            dataOutputStream.write(arr);
        }
        System.out.println("对象写入完毕~");
    }
}
